# 支付接口
import requests
import hashlib
from django.http import HttpResponse


# 异步通知API
def async_notify(request):
    print(request.GET)
    return HttpResponse("success")


# 创建支付参数
def create_pay_params(paytype="alipay", out_trade_no="123456789", money=1, name="测试商品", clientip="127.0.0.1"):
    params = {
        "pid": "1397",
        "type": paytype,
        "out_trade_no": out_trade_no,
        "return_url": "http://za2ba9e8.natappfree.cc/api/pay/v1/notify/",
        "notify_url": "http://za2ba9e8.natappfree.cc/api/pay/v1/notify/",
        "name": name,
        "money": money,
        "clientip":clientip,
        "sign": "",
        "sign_type": "MD5"
        
    }
    # 按参数名排序
    sorted_params = sorted(params.items(), key=lambda x: x[0])

    # 拼接参数
    param_str = '&'.join([f"{k}={v}" for k, v in sorted_params if v and k not in ['sign', 'sign_type']])

    # 计算签名
    sign_str = param_str + "grbCK5VLvWoIeyKjjIijEPZTsdKIolUR"
    md5 = hashlib.md5()
    md5.update(sign_str.encode('utf-8'))
    sign = md5.hexdigest()
    params["sign"] = sign
    # 返回支付参数
    return params


# 创建支付链接
def create_pay_link():
    params = create_pay_params()
    pay_responses = requests.post("https://e.heiyu.cc/mapi.php", data=params,headers={
        "Content-Type": "application/x-www-form-urlencoded"
    }).json()
    return pay_responses

